<template>
  <!-- 使用 Element Plus 的空间分隔组件（el-space）来排列选择框 -->
  <el-space style="width: 100%">
    <!-- 第一级下拉选择框：所在省 -->
    <el-select
      :class="{ 'w-input': isW }"
      clearable
      v-model="area_data.value[0]"
      placeholder="所在省"
      size="large"
      @change="
        (value) => {
          handleValueChange(value, 0);
        }
      "
      @clear="
        (value) => {
          handleValueClear(value, 0);
        }
      "
      :disabled="disabled"
    >
      <!-- 循环渲染第一级选项 -->
      <el-option
        v-for="item in list_1"
        :key="item.districtId"
        :label="item.district"
        :value="item.districtId"
      />
    </el-select>
    <!-- 第二级下拉选择框：所在市 -->
    <el-select
      :class="{ 'w-input': isW }"
      clearable
      v-model="area_data.value[1]"
      placeholder="所在市"
      size="large"
      v-if="props.showMarket"
      :disabled="!area_data.value[0] || disabled"
      @change="
        (value) => {
          handleValueChange(value, 1);
        }
      "
      @clear="
        (value) => {
          handleValueClear(value, 0);
        } // 清空时的事件处理
      "
    >
      <!-- 循环渲染第二级选项 -->
      <el-option
        v-for="item in area_data.data[1]"
        :key="item.districtId"
        :label="item.district"
        :value="item.districtId"
      />
    </el-select>
    <!-- 第三级下拉选择框：所在区/县 -->
    <el-select
      :class="{ 'w-input': isW }"
      clearable
      v-model="area_data.value[2]"
      placeholder="所在区/县"
      size="large"
      :disabled="!area_data.value[1] || disabled"
      @change="
        (value) => {
          handleValueChange(value, 2);
        }
      "
      @clear="
        (value) => {
          handleValueClear(value, 0);
        }
      "
      v-if="props.showCounty"
    >
      <!-- 循环渲染第三级选项 -->
      <el-option
        v-for="item in area_data.data[2]"
        :key="item.districtId"
        :label="item.district"
        :value="item.districtId"
      /> </el-select
  ></el-space>
</template>

<script setup>
import { computed, onMounted, ref, watch } from "vue";
import { getAreaApi } from "@/api/common"; //导入获取地区数据的API
//定义组件接收的props
const props = defineProps({
  economize: {
    default: "",
    type: String,
  },
  market: "",
  county: "",
  showMarket: {
    default: true,
    type: Boolean,
  },
  showCounty: {
    default: false,
    type: Boolean,
  },
  disabled: {
    default: false,
    type: Boolean,
  },
  isW: {
    default: false,
    type: Boolean,
  },
  addChina: {
    default: false,
    type: Boolean,
  },
});
const emit = defineEmits([
  "update:economize",
  "update:market",
  "update:county",
]);
const area_data = ref({
  value: ["", "", ""],
  data: [[], [], []],
  map: {},
});
/**
 * 获取lv1
 */
const handleGetArea = async (pid, index = 0) => {
  let entityList = [];
  const area_data_map = localStorage.getItem("area_data_map") ?? null;

  if (area_data.value.map[pid]) {
    entityList = area_data.value.map[pid];
  } else {
    let bool = false;
    if (area_data_map) {
      try {
        if (JSON.parse(area_data_map)[pid]) {
          entityList = JSON.parse(area_data_map)[pid];
          bool = true;
        }
      } catch (error) {
        bool = false;
      }
    }
    if (!bool) {
      let res = await getAreaApi(pid);
      if (res.success) {
        entityList = res.entityList;
      }
    }
  }
  area_data.value.data[index] = entityList;
  area_data.value.map[pid] = entityList;
  localStorage.setItem("area_data_map", JSON.stringify(area_data.value.map));
};

//初始化地区数据的函数
const handleInit = async () => {
  await handleGetArea(1, 0);
  if (props.economize && props.market && props.county) {
    await handleGetArea(props.economize, 1);
    await handleGetArea(props.market, 2);
    const economize = area_data.value.data[0].find(
      (item) => item.districtId == String(props.economize)
    )
      ? props.economize
      : "";
    const market = area_data.value.data[1].find(
      (item) => item.districtId == String(props.market)
    )
      ? props.market
      : "";
    const county = area_data.value.data[2].find(
      (item) => item.districtId == String(props.county)
    )
      ? props.county
      : "";
    area_data.value.value = [economize, market, county];
  } else if (props.economize && props.market) {
    await handleGetArea(props.economize, 1);
    area_data.value.value = [props.economize, props.market, ""];
  } else if (props.economize) {
    await handleGetArea(props.economize, 1);
    area_data.value.value = [props.economize, "", ""];
  } else if (!props.economize && !props.market && !props.county) {
    area_data.value.value = ["", "", ""];
  }
};
// 监听props变化，重新初始化地区数据
watch(
  () => props.economize,
  () => {
    handleInit();
  }
);
watch(
  () => props.market,
  () => {
    handleInit();
  }
);
watch(
  () => props.county,
  () => {
    handleInit();
  }
);

// 处理值变化的函数
const handleValueChange = (value, index) => {
  if (index == 0) {
    area_data.value.value[1] = "";
    area_data.value.value[2] = "";
    handleGetArea(value, 1);
  } else if (index == 1) {
    area_data.value.value[2] = "";
    handleGetArea(value, 2);
    if (!props.showCounty) {
      //   handleChange("economize", 0);
      //   handleChange("market", 1);
    }
  } else if (index == 2) {
    // handleChange("economize", 0);
    // handleChange("market", 1);
    // handleChange("county", 2);
  }
  handleChange("economize", 0);
  handleChange("market", 1);
  handleChange("county", 2);
};

// 处理值清空的函数
const handleValueClear = (value, index) => {
  if (index == 0) {
    area_data.value.value[0] = "";
    area_data.value.value[1] = "";
    area_data.value.value[2] = "";
    handleChange("economize", 0);
    handleChange("market", 1);
    handleChange("county", 2);
  } else if (index == 1) {
    area_data.value.value[1] = "";
    area_data.value.value[2] = "";
    handleChange("market", 1);
    handleChange("county", 2);
  } else if (index == 2) {
    area_data.value.value[2] = "";
    handleChange("county", 2);
  }
};

//处理值变化并触发emit的函数
const handleChange = (key = "economize", index = 0) => {
  let values = area_data.value.value;
  emit("update:" + key, values[index]);
};

// 计算属性，用于获取第一级选项列表
const list_1 = computed(() => {
  let arr = [];
  if (props.addChina) {
    arr.push({
      districtId: 1,
      district: "中国",
    });
  }
  arr.push(...area_data.value.data[0]);
  return arr;
});

// 组件挂载后执行的函数
onMounted(() => {
  handleInit();
});
</script>

<style lang="scss" scoped>
.w-input {
  width: 120px;

  :deep(.el-input) {
    width: 120px;
  }

  .el-input-number {
    width: 120px;
  }
}
</style>